package com.redwine.app;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.redwine.app.net.GsonRequest;
import com.redwine.app.net.NetworkConstants;
import com.redwine.app.net.responses.BaseResponse;
import com.redwine.app.net.responses.CommonListDataResponse;
import com.redwine.app.net.responses.LoginResponse;
import com.redwine.app.utils.NetUtil;
import com.redwine.app.utils.Utils;

import java.util.LinkedHashMap;
import java.util.Map;

public class LoginRegisterActivity extends BaseActivity implements View.OnClickListener {

    @ViewInject(R.id.register_tv_title)
    private TextView registerTvTitle;
    @ViewInject(R.id.register_bt)
    private Button registerBt;
    @ViewInject(R.id.register_et_phone_number)
    private EditText registerEtPhoneNumber;
    @ViewInject(R.id.register_et_security_code)
    private EditText registerEtSecurityCode;
    @ViewInject(R.id.register_et_password)
    private EditText registerEtPassword;
    @ViewInject(R.id.register_ll_nickname)
    LinearLayout layoutNickName;
    @ViewInject(R.id.register_et_security_nickname)
    private EditText registerEtNickName;
    @ViewInject(R.id.register_tv_send_security_code)
    private TextView mTvSecurity_code;
    public static final String IS_REGISTERED = "IS_REGISTERED";
    private boolean isRegistered = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_register_main);
        ViewUtils.inject(this);
        initView();
    }

    private void initView() {
        Intent intent = getIntent();
        if (null != intent) {
            isRegistered = intent.getBooleanExtra(IS_REGISTERED, false);
        } else {
            finish();
        }
        if (isRegistered) {
            layoutNickName.setVisibility(View.VISIBLE);
            registerTvTitle.setText(getString(R.string.login_register_name));
            registerBt.setText(getString(R.string.login_register));
        } else {
            layoutNickName.setVisibility(View.GONE);
            registerTvTitle.setText(getString(R.string.login_forget_password));
            registerBt.setText(getString(R.string.submit));
        }
    }

    @OnClick({R.id.register_bt, R.id.register_tv_send_security_code, R.id.register_tv_back})
    public void mClick(View v) {
        switch (v.getId()) {

            case R.id.register_bt:
                submit();
                break;

            case R.id.register_tv_send_security_code:
                String checkPhoneNum = checkPhoneNum();
                if (!TextUtils.isEmpty(checkPhoneNum))
                    requestSendSmsData(checkPhoneNum);
                break;

            case R.id.register_tv_back:
                finish();
                break;
        }
    }

    private String checkPhoneNum() {
        String number = registerEtPhoneNumber.getText().toString().trim();
        if (TextUtils.isEmpty(number)) {
            Toast.makeText(this, "手机号码不能为空！", Toast.LENGTH_SHORT).show();
            return "";
        }
        return number;
    }

    private void submit() {
        // validate
        String checkPhoneNum = checkPhoneNum();
        if (TextUtils.isEmpty(checkPhoneNum))
            return;

        String code = registerEtSecurityCode.getText().toString().trim();
        if (TextUtils.isEmpty(code)) {
            Toast.makeText(this, "验证码不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }

        String password = registerEtPassword.getText().toString().trim();
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "密码不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }
        if (password.length() < 6) {
            Toast.makeText(this, "密码格式不正确", Toast.LENGTH_SHORT).show();
            return;
        }

        if (isRegistered) {
            String nickName = registerEtNickName.getText().toString().trim();
            if (TextUtils.isEmpty(nickName)) {
                Toast.makeText(this, "昵称不能为空！", Toast.LENGTH_SHORT).show();
                return;
            }
            requestRegisterData(checkPhoneNum, code, password, nickName);
        } else {
            requestForgetData(checkPhoneNum, code, password);
        }
    }

    /**
     * 注册接口
     * 作者：gassion on 17/8/17 00:20
     * 最可怕的敌人，就是没有坚强的信念。
     */
    protected void requestRegisterData(String phoneNumber, String code, String password, String nickName) {
        if (!NetUtil.checkNet(this)) {
            Utils.showToast(R.string.generic_check);
            return;
        }

        showWaiting();
        String url = NetworkConstants.REGISTER_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("mobile", phoneNumber);
        params.put("code", code);
        params.put("password", password);
        params.put("nickname", nickName);
        GsonRequest<BaseResponse> request = new GsonRequest<>(url, Request.Method.POST,
                BaseResponse.class, false, params, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                dismissWaiting();
                Utils.showToast(response.getMsg());
                if (response.isSuccess()) {
                    finish();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissWaiting();
                Utils.showToast(error.getMessage());
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }

    /**
     * 忘记密码
     * 作者：gassion on 17/8/26 16:15
     * 最可怕的敌人，就是没有坚强的信念。
     */
    protected void requestForgetData(final String phoneNumber, String code, final String password) {
        if (!NetUtil.checkNet(this)) {
            Utils.showToast(R.string.generic_check);
            return;
        }

        showWaiting();
        String url = NetworkConstants.SAVE_PASSWORD_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("mobile", phoneNumber);
        params.put("code", code);
        params.put("password", password);
        final GsonRequest<LoginResponse> request = new GsonRequest<>(url, Request.Method.POST,
                LoginResponse.class, false, params, new Response.Listener<LoginResponse>() {
            @Override
            public void onResponse(LoginResponse response) {
                dismissWaiting();
                Utils.showToast(response.getMsg());
                if (response.isSuccess()) {
                    finish();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissWaiting();
                Utils.showToast(error.getMessage());
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }

    /**
     * 发送验证码
     * 作者：gassion on 17/8/17 00:20
     * 最可怕的敌人，就是没有坚强的信念。
     */
    protected void requestSendSmsData(String phone) {
        showWaiting();
        String url = NetworkConstants.SEND_SMS_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("mobile", phone);
        GsonRequest<CommonListDataResponse> request = new GsonRequest<>(url, Request.Method.POST,
                CommonListDataResponse.class, false, params, new Response.Listener<CommonListDataResponse>() {
            @Override
            public void onResponse(CommonListDataResponse response) {
                dismissWaiting();
                Utils.showToast(response.getMsg());
                if (response.isSuccess()) {
                    timer.start();
                    mTvSecurity_code.setEnabled(false);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissWaiting();
                Utils.showToast(error.getMessage());
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }

    /**
     * 设置定时
     */
    private CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mTvSecurity_code.getLayoutParams();
            lp.setMargins(0, 0, 60, 0);
            mTvSecurity_code.setLayoutParams(lp);
            mTvSecurity_code.setText(millisUntilFinished / 1000 + " S");
        }

        @Override
        public void onFinish() {
            timer.cancel();
            mTvSecurity_code.setEnabled(true);
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mTvSecurity_code.getLayoutParams();
            lp.setMargins(0, 0, 0, 0);
            mTvSecurity_code.setLayoutParams(lp);
            mTvSecurity_code.setText("获取验证码");
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }
}
